﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

namespace MachineBuildingSystem
{
    public partial class BackConcreteUC : UserControl
    {
        private string m_CurrentUser = "";
        private string m_Password = "";
        //操作权限
        private List<long> m_ActionList = new List<long>();

        //当前发货列表
        private DataTable m_DeliveryDT = new DataTable();

        private OrderInfo m_CurrentOrder = new OrderInfo();

        private DataTable m_BindDT = null;
        public BackConcreteUC()
        {
            InitializeComponent();
        }

        public void RefreshBackConcrete(string currentUser, string password, List<long> actionList, DataTable deliveryDT, OrderInfo currentOrder)
        {
            m_CurrentUser = currentUser;
            m_Password = password;
            m_ActionList = actionList;
            m_DeliveryDT = deliveryDT.Clone();
            foreach (DataRow dr in deliveryDT.Rows)
            {
                if (Convert.ToDecimal(dr["deliQuantity"]) < 0)
                    continue;
                m_DeliveryDT.Rows.Add(dr.ItemArray);
            }

            m_CurrentOrder = currentOrder;
            //绑定发货单列表
            gdcProduct.DataSource = m_DeliveryDT;

            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += backgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
            backgroundWorker.RunWorkerAsync();
        }

        private BackConcreteInfo m_BackConcreteInfo = null;
        private void btnBackConcrete_Click(object sender, EventArgs e)
        {
            if (!m_ActionList.Contains((int)ActionEnum.BackConcrete))
            {
                MessageBox.Show(this, "该用户无退砼权限！");
                return;
            }
            DataRow currentRow = this.gdvProduct.GetFocusedDataRow();
            if (currentRow == null)
            {
                MessageBox.Show(this, "请先选择需要退砼的发货单!");
                return;
            }
            if (!string.IsNullOrEmpty(currentRow["returnStatus"].ToString()))
            {
                MessageBox.Show(this, "该发货单已进行退砼处理，不能再进行退砼!");
                return;
            }
            if (DialogResult.Yes != MessageBox.Show(this, "是否确认对该发货单进行退砼处理？", "",
             MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                return;
            long deliveryId = Convert.ToInt64(currentRow["deliId"]);

            m_BackConcreteInfo = new BackConcreteInfo();
            m_BackConcreteInfo.DeliveryId = deliveryId;
            //获取退砼信息
            this.backConcreteBaseInfo.GetBackConcreteBaseInfo(ref m_BackConcreteInfo);
            if (m_BackConcreteInfo.Number <= 0)
            {
                MessageBox.Show(this, "请先选择退砼数量!");
                return;
            }
            decimal deliQuantity = Convert.ToDecimal(currentRow["deliQuantity"]);
            //如果退砼数量大于发货单数量给出提示
            if (m_BackConcreteInfo.Number > deliQuantity)
            {
                MessageBox.Show(this, "退砼数量不能大于发货单数量!");
                return;
            }
            //根据退砼状态判断是否需要选择订单
            if (m_BackConcreteInfo.State == (int)BackConcreteStatusEnum.Recovery
                || m_BackConcreteInfo.State == (int)BackConcreteStatusEnum.BackConcrete)
            {
                List<DataRow> selectedRowList = new List<DataRow>();
                for (int i = 0; i < gdvOrder.RowCount; i++)
                {
                    DataRow row = gdvOrder.GetDataRow(i);
                    if (Convert.ToBoolean(row["Checked"]) == true)
                        selectedRowList.Add(row);
                }
                if (selectedRowList.Count == 0)
                {
                    MessageBox.Show(this, "请勾选订单!");
                    return;
                }
                if (selectedRowList.Count > 2)
                {
                    MessageBox.Show(this, "有且只能选择一个订单!");
                    return;
                }
                long orderId = Convert.ToInt64(selectedRowList[0]["Id"].ToString());
                m_BackConcreteInfo.OrderId = orderId;
            }
            try
            {
                if (!DataHelper.SaveReturnSale(m_CurrentUser, m_Password, m_BackConcreteInfo))
                    return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "退砼保存失败:" + ex.Message);
                return;
            }
            MessageBox.Show(this, "退砼保存成功！");
            BackgroundWorker backgroundWorker_deli = new BackgroundWorker();
            backgroundWorker_deli.DoWork += backgroundWorker_deli_DoWork;
            backgroundWorker_deli.RunWorkerCompleted += backgroundWorker_deli_RunWorkerCompleted;
            backgroundWorker_deli.RunWorkerAsync(m_CurrentOrder.id);
        }

        public delegate void BackConcreteCloseEventHandler(object sender, EventArgs e);
        public event BackConcreteCloseEventHandler BackConcreteCloseEvent;
        private void btnClose_Click(object sender, EventArgs e)
        {
            if (BackConcreteCloseEvent != null)
                BackConcreteCloseEvent(this, e);
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<OrderInfo> orderList = null;
            try
            {
                int belongcorpId = int.Parse(ConfigurationManager.AppSettings["BelongCorpId"]);
                string types = ((int)ExecuteStatusEnum.EXECUTE).ToString() + ":" + ((int)ExecuteStatusEnum.UN_EXECUTE).ToString();
                //发往其他工地的订单需是已执行和未执行的订单且已审核（之后无需控制是否是本客户下的订单）
                orderList = DataHelper.GetSaleOrders(m_CurrentUser, m_Password, belongcorpId, 0, "", 0, 0, DateTime.MinValue, DateTime.MaxValue, types, "1", 0, 200);
            }
            catch
            {
                throw;
            }
            e.Result = orderList;
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;
            if (e.Error != null)
            {
                MessageBox.Show(this, e.Error.Message);
                return;
            }
            List<OrderInfo> orderList = e.Result as List<OrderInfo>;
            if (orderList == null || orderList.Count == 0)
                return;
            //按ID进行排序
            var query = from temp in orderList
                        orderby temp.id ascending
                        select temp;

            List<OrderInfo> tempList = new List<OrderInfo> ();
            foreach (OrderInfo order in query)
            {
                //过滤本订单
                if (order.id == m_CurrentOrder.id)
                    continue;
                tempList.Add(order);
            }
            try
            {
                BindData(tempList);
            }
            catch (Exception ex)
            {
                LogHelper.error("绑定订单列表异常：" + ex.ToString());
            }
            if (m_BackConcreteInfo == null)
                return;
            if (m_BackConcreteInfo.State == (int)BackConcreteStatusEnum.Recovery
                 || m_BackConcreteInfo.State == (int)BackConcreteStatusEnum.BackConcrete)
            {
                BackgroundWorker backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += backgroundWorker_DoWork;
                backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
                backgroundWorker.RunWorkerAsync();
            }
        }

        //绑定列表
        private void BindData(List<OrderInfo> orderList)
        {
            try
            {
                foreach (OrderInfo order in orderList)
                    m_BindDT.Rows.Add(false, order.mainId, order.id, order.orderCode, order.orderDate.ToString("yyyy-MM-dd"),
                        order.customerId, order.customerCode, order.customerName,order.corpName,
                        order.materialId, order.materialCode, order.materialName, order.materialSstd,order.strengthGrade,
                        order.projectName, order.constructSite, order.orderQuantity, order.sendQuantity, 
                        order.executeStatus == (int)ExecuteStatusEnum.UN_EXECUTE ? "未执行" :
                        (order.executeStatus == (int)ExecuteStatusEnum.EXECUTE ? "执行" :
                        (order.executeStatus == (int)ExecuteStatusEnum.PAUSE ? "作废" : "关闭")));
                gdcOrder.DataSource = m_BindDT;
            }
            catch (Exception ex)
            {
                LogHelper.error("绑定订单列表异常：" + ex.ToString());
            }
        }

        private void InitDT()
        {
            m_BindDT = new DataTable();
            m_BindDT.Columns.Add("Checked",typeof(bool));
            m_BindDT.Columns.Add("mainId");
            m_BindDT.Columns.Add("id");
            m_BindDT.Columns.Add("orderCode");
            m_BindDT.Columns.Add("orderDate");
            m_BindDT.Columns.Add("customerId");
            m_BindDT.Columns.Add("customerCode");
            m_BindDT.Columns.Add("customerName");
            m_BindDT.Columns.Add("corpName");
            m_BindDT.Columns.Add("materialId");
            m_BindDT.Columns.Add("materialCode");
            m_BindDT.Columns.Add("materialName");
            m_BindDT.Columns.Add("materialSstd");
            m_BindDT.Columns.Add("strengthGrade");
            m_BindDT.Columns.Add("projectName");
            m_BindDT.Columns.Add("constructionSite");
            m_BindDT.Columns.Add("orderQuantity");
            m_BindDT.Columns.Add("sendQuantity");
            m_BindDT.Columns.Add("executeStatus");
        }

        private void BackConcreteUC_Load(object sender, EventArgs e)
        {
            InitDT();
        }

        private void repositoryItemCheckEdit_CheckedChanged(object sender, EventArgs e)
        {
            DataTable dt = this.gdcOrder.DataSource as DataTable;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["Checked"] = false;
            }
            gdcOrder.RefreshDataSource();
        }

        //订单列表行变化时更新工地名称
        private void gdvOrder_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            string projectName = "";
            DataRow currentRow = gdvOrder.GetFocusedDataRow();
            if (currentRow == null)
                projectName = "";
            else
                projectName = currentRow["projectName"].ToString();

            this.backConcreteBaseInfo.SetProjectName(projectName);
        }

        private void backgroundWorker_deli_DoWork(object sender, DoWorkEventArgs e)
        {
            List<DeliveryInfo> deliveryInfoList = null;
            long orderId = Convert.ToInt64(e.Argument);
            try
            {
                deliveryInfoList = DataHelper.GetSaleDeliverys(m_CurrentUser, m_Password, orderId);
            }
            catch (Exception ex)
            {
                throw new Exception("根据订单ID：" + orderId + "获取发货单详情异常：" + ex.Message);
            }
            e.Result = deliveryInfoList;
        }

        private void backgroundWorker_deli_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                return;
            if (e.Error != null)
            {
                LogHelper.error(e.Error.Message);
                MessageBox.Show(e.Error.Message);
                return;
            }
            //绑定发货单列表
            m_DeliveryDT.Clear();
            gdcProduct.DataSource = m_DeliveryDT;
            List<DeliveryInfo> deliveryInfoList = e.Result as List<DeliveryInfo>;
            if (deliveryInfoList == null || deliveryInfoList.Count == 0)
                return;
            BindData(deliveryInfoList);
        }

        private void BindData(List<DeliveryInfo> deliveryInfoList)
        {
            try
            {
                string returnStatus = "";
                foreach (DeliveryInfo deliveryInfo in deliveryInfoList)
                {
                    if (deliveryInfo.deliQuantity < 0)
                        continue;
                    switch (deliveryInfo.returnStatus)
                    {
                        case (int)ReturnStatusEnum.ALLSIGNS_WASTE:
                            returnStatus = "全部签收，废料处理";
                            break;
                        case (int)ReturnStatusEnum.ALLSIGNS_SELF:
                            returnStatus = "全部签收，直接发往本客户其他工地";
                            break;
                        case (int)ReturnStatusEnum.ALLSIGNS_OTHER:
                            returnStatus = "全部签收，调料后发往其他工地";
                            break;
                        case (int)ReturnStatusEnum.PARTSIGNS_WASTE:
                            returnStatus = "部分签收，废料处理";
                            break;
                        case (int)ReturnStatusEnum.PARTSIGNS_SELF:
                            returnStatus = "部分签收，直接发往本客户其他工地";
                            break;
                        case (int)ReturnStatusEnum.PARTSIGNS_OTHER:
                            returnStatus = "部分签收，调料后发往其他工地";
                            break;
                        case (int)ReturnStatusEnum.ALLOCATE_SELF:
                            returnStatus = "调拨发货，发往本客户其他工地";
                            break;
                        case (int)ReturnStatusEnum.RETURN_OTHER:
                            returnStatus = "剩余发货，发往其他工地";
                            break;
                        case (int)ReturnStatusEnum.PART_BACK:
                            returnStatus = "部分退货";
                            break;
                        default:
                            returnStatus = "";
                            break;
                    }
                    m_DeliveryDT.Rows.Add(deliveryInfo.id, deliveryInfo.deliDate, deliveryInfo.deliQuantity,
                        deliveryInfo.recoveredQuantity, deliveryInfo.productQuantity, deliveryInfo.workingCenterName,
                        deliveryInfo.carCode, deliveryInfo.driverName, deliveryInfo.makerName, returnStatus, deliveryInfo.returnQuantity, deliveryInfo.remarks);
                }
                this.gdcProduct.DataSource = m_DeliveryDT;
            }
            catch (Exception ex)
            {
                LogHelper.error("绑定发货单列表异常：" + ex.ToString());
                MessageBox.Show("绑定发货单列表异常:" + ex.Message);
            }
        }

        private void gdvProduct_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gdvOrder_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
    }
}
